package com.young.gpg.common.util;

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Objects;
import java.util.Properties;
import java.util.Vector;

/**
 * @description：sftp工具类
 * @author: yangyahui01
 * @date: 12/4/24 10:00 PM
 */
@Slf4j
public class SFTPUtil {

    private String userName;

    private String passWord;

    private int port;

    private String hostName;

    private String privateKeyFile;

    private String passPhrase;

    Session session = null;

    Channel channel = null;

    public SFTPUtil(String userName, String passWord, String hostName, int port) {
        this.userName = userName;
        this.passWord = passWord;
        this.hostName = hostName;
        this.port = port;
    }

    public SFTPUtil(String userName, String passWord, int port, String hostName, String privateKeyFile, String passPhrase) {
        this.userName = userName;
        this.passWord = passWord;
        this.port = port;
        this.hostName = hostName;
        this.privateKeyFile = privateKeyFile;
        this.passPhrase = passPhrase;
    }

    public ChannelSftp connect() {
        JSch jSch = new JSch();

        try {
            if (port > 0) {
                session = jSch.getSession(userName, hostName, port);
            } else {
                session = jSch.getSession(userName, hostName);
            }


            if (session == null) {
                return null;
            }

            session.setPassword(passWord);

            Properties config = new Properties();

            config.put("StrictHostKeyChecking", "no");

            session.setConfig(config);

            session.setTimeout(200000);

            session.connect();

            channel = session.openChannel("sftp");

            channel.connect();

            return (ChannelSftp) channel;


        } catch (JSchException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 密钥文件连接
     *
     * @return
     */
    public ChannelSftp privateKeyChannel() {
        JSch jSch = new JSch();

        try {
            if (Objects.nonNull(privateKeyFile) && !"".equals(privateKeyFile)) {
                log.info("存在privateKeyFile:{}", privateKeyFile);

                if (Objects.nonNull(passPhrase) && !"".equals(passPhrase)) {
                    jSch.addIdentity(privateKeyFile, passPhrase);
                } else {
                    jSch.addIdentity(privateKeyFile);
                }
            }

            log.info("add privateKeyFile 成功");

            if (port > 0) {
                session = jSch.getSession(userName, hostName, port);
            } else {
                session = jSch.getSession(userName, hostName);
            }

            log.info("session成功");

            Properties config = new Properties();

            config.put("StrictHostKeyChecking", "no");

            session.setConfig(config);

            session.setTimeout(200000);

            log.info("connect开始");

            session.connect();

            log.info("connect成功");

            channel = session.openChannel("sftp");

            channel.connect();

            return (ChannelSftp) channel;
        } catch (JSchException e) {
            log.error("连接创建失败:", e);
        }
        return null;
    }


    /**
     *
     * @param is 要上传的本地文件流
     * @param dsc 目标目录或文件，若是目录则上传的目标文件名和本地文件名一样
     * @param sftp
     * @return
     */
    public boolean upload(InputStream is, String dsc, ChannelSftp sftp) {
        try {
            sftp.put(is, dsc);
            return true;
        } catch (SftpException e) {
            log.error("upload error", e);
            return false;
        }
    }


    public boolean upload(String remoteDir, String uploadFile, ChannelSftp sftp) {
        try {
            sftp.cd(remoteDir);
            File file = new File(uploadFile);
            sftp.put(new FileInputStream(file), file.getName());
            return true;
        } catch (SftpException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return false;

    }

    /**
     * 下载文件
     *
     * @param directory
     * 下载目录
     * @param downloadFile
     * 下载的文件
     * @param saveFile
     * 存在本地的路径
     * @param sftp
     */
    public void download(String directory, String downloadFile,
                         String saveFile, ChannelSftp sftp) {
        try {
            sftp.cd(directory);
            sftp.get(downloadFile,saveFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除文件
     *
     * @param directory
     * 要删除文件所在目录
     * @param deleteFile
     * 要删除的文件
     * @param sftp
     */
    public void delete(String directory, String deleteFile, ChannelSftp sftp) {
        try {
            sftp.cd(directory);
            sftp.rm(deleteFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * 列出目录下的文件
     *
     * @param directory：要列出的目录
     * @param sftp
     * @return
     * @throws SftpException
     */
    public Vector listFiles(String directory, ChannelSftp sftp) throws SftpException {
        return sftp.ls(directory);
    }


    public void disconnected(ChannelSftp sftp){
        if (sftp != null) {
            try {
                sftp.getSession().disconnect();
            } catch (JSchException e) {
                e.printStackTrace();
            }
            sftp.disconnect();
        }
    }
}
